package com.nutrition.health.service.impl;

import com.nutrition.health.model.DietRecord;
import com.nutrition.health.model.DietRecord.MealType;
import com.nutrition.health.model.FoodItem;
import com.nutrition.health.model.FoodItem.FoodCategory;
import com.nutrition.health.model.NutritionInfo;
import com.nutrition.health.model.User;
import com.nutrition.health.model.UserHealthProfile;
import com.nutrition.health.repository.DietRecordRepository;
import com.nutrition.health.repository.FoodItemRepository;
import com.nutrition.health.repository.NutritionInfoRepository;
import com.nutrition.health.repository.UserHealthProfileRepository;
import com.nutrition.health.repository.UserRepository;
import com.nutrition.health.service.DeepSeekAIService;
import com.nutrition.health.service.DietRecordService;
import com.nutrition.health.service.UserHealthProfileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.Comparator;

@Service
@Transactional
public class DietRecordServiceImpl implements DietRecordService {

    private static final Logger logger = LoggerFactory.getLogger(DietRecordServiceImpl.class);

    private final DietRecordRepository dietRecordRepository;
    private final UserRepository userRepository;
    private final FoodItemRepository foodItemRepository;
    private final NutritionInfoRepository nutritionInfoRepository;
    private final UserHealthProfileService userHealthProfileService;
    private final DeepSeekAIService deepSeekAIService;
    private final UserHealthProfileRepository userHealthProfileRepository;

    @Autowired
    public DietRecordServiceImpl(
            DietRecordRepository dietRecordRepository,
            UserRepository userRepository,
            FoodItemRepository foodItemRepository,
            NutritionInfoRepository nutritionInfoRepository,
            UserHealthProfileService userHealthProfileService,
            DeepSeekAIService deepSeekAIService,
            UserHealthProfileRepository userHealthProfileRepository) {
        this.dietRecordRepository = dietRecordRepository;
        this.userRepository = userRepository;
        this.foodItemRepository = foodItemRepository;
        this.nutritionInfoRepository = nutritionInfoRepository;
        this.userHealthProfileService = userHealthProfileService;
        this.deepSeekAIService = deepSeekAIService;
        this.userHealthProfileRepository = userHealthProfileRepository;
    }

    @Override
    public List<DietRecord> getAllDietRecordsByUserId(Long userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found with id: " + userId));

        return dietRecordRepository.findByUserId(userId);
    }

    @Override
    public Page<DietRecord> getAllDietRecordsByUserId(Long userId, Pageable pageable) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found with id: " + userId));

        return dietRecordRepository.findByUserId(userId, pageable);
    }

    @Override
    public Optional<DietRecord> getDietRecordById(Long id) {
        return dietRecordRepository.findById(id);
    }

    @Override
    public List<DietRecord> getDietRecordsByUserIdAndMealType(Long userId, MealType mealType) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found with id: " + userId));

        return dietRecordRepository.findByUserIdAndMealType(userId, mealType);
    }

    @Override
    public List<DietRecord> getDietRecordsByUserIdAndDateRange(Long userId, LocalDate startDate, LocalDate endDate) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found with id: " + userId));

        LocalDateTime startDateTime = startDate.atStartOfDay();
        LocalDateTime endDateTime = endDate.atTime(LocalTime.MAX);

        return dietRecordRepository.findByUserIdAndConsumptionTimeBetween(userId, startDateTime, endDateTime);
    }

    @Override
    public DietRecord createDietRecord(Long userId, DietRecord dietRecord) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found with id: " + userId));

        dietRecord.setUserId(userId);
        
        // 初始化营养值
        dietRecord.setCalories(0.0);
        dietRecord.setProtein(0.0);
        dietRecord.setCarbohydrates(0.0);
        dietRecord.setFat(0.0);
        
        // 保存记录以获取ID
        DietRecord savedRecord = dietRecordRepository.save(dietRecord);
        
        return savedRecord;
    }

    @Override
    public DietRecord updateDietRecord(Long id, DietRecord dietRecordDetails) {
        DietRecord dietRecord = dietRecordRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Diet record not found with id: " + id));

        dietRecord.setConsumptionTime(dietRecordDetails.getConsumptionTime());
        dietRecord.setMealType(dietRecordDetails.getMealType());
        dietRecord.setNotes(dietRecordDetails.getNotes());

        // 不直接更新食品列表，应该通过专门的方法添加或移除食品

        return dietRecordRepository.save(dietRecord);
    }

    @Override
    public void deleteDietRecord(Long id) {
        dietRecordRepository.deleteById(id);
    }

    @Override
    public DietRecord addFoodItemToDietRecord(Long dietRecordId, Long foodItemId) {
        DietRecord dietRecord = dietRecordRepository.findById(dietRecordId)
                .orElseThrow(() -> new RuntimeException("Diet record not found with id: " + dietRecordId));

        // 检查食物是否存在，如果不存在则创建
        FoodItem foodItem;
        Optional<FoodItem> existingFoodItem = foodItemRepository.findById(foodItemId);
        
        if (existingFoodItem.isPresent()) {
            foodItem = existingFoodItem.get();
        } else {
            // 如果食物不存在，则创建一个新的食物项
            // 这种情况通常不会发生，因为前端应该已经创建了食物项
            // 但为了健壮性，我们还是处理这种情况
            logger.warn("Food item not found with id: {}. Creating a new one.", foodItemId);
            foodItem = new FoodItem();
            foodItem.setName("未知食物");
            foodItem.setCategory(FoodCategory.OTHER);
            foodItem = foodItemRepository.save(foodItem);
        }

        // 添加食物到饮食记录
        dietRecord.getFoodItems().add(foodItem);
        
        // 计算营养信息
        calculateAndUpdateNutrition(dietRecord);
        
        // 保存更新后的饮食记录
        return dietRecordRepository.save(dietRecord);
    }
    
    /**
     * 计算并更新饮食记录的营养信息
     * @param dietRecord 饮食记录
     */
    private void calculateAndUpdateNutrition(DietRecord dietRecord) {
        // 重置营养值
        double totalCalories = 0.0;
        double totalProtein = 0.0;
        double totalCarbs = 0.0;
        double totalFat = 0.0;
        
        // 遍历所有食物项，计算总营养值
        for (FoodItem foodItem : dietRecord.getFoodItems()) {
            try {
                // 获取食物的营养信息
                NutritionInfo nutritionInfo = null;
                Optional<NutritionInfo> existingNutritionInfo = nutritionInfoRepository.findByFoodItemId(foodItem.getId());
                
                if (existingNutritionInfo.isPresent()) {
                    // 如果已有营养信息，直接使用
                    nutritionInfo = existingNutritionInfo.get();
                } else {
                    // 如果没有营养信息，调用DeepSeek AI计算
                    Map<String, Double> nutritionData = deepSeekAIService.calculateNutrition(foodItem.getName(), 100.0);
                    
                    // 创建新的营养信息
                    nutritionInfo = new NutritionInfo();
                    nutritionInfo.setFoodItemId(foodItem.getId());
                    nutritionInfo.setServingSize(100.0); // 默认100克
                    nutritionInfo.setCalories(nutritionData.getOrDefault("calories", 0.0));
                    nutritionInfo.setProtein(nutritionData.getOrDefault("protein", 0.0));
                    nutritionInfo.setCarbohydrates(nutritionData.getOrDefault("carbohydrates", 0.0));
                    nutritionInfo.setFat(nutritionData.getOrDefault("fat", 0.0));
                    
                    // 保存营养信息
                    nutritionInfo = nutritionInfoRepository.save(nutritionInfo);
                }
                
                // 累加营养值
                totalCalories += nutritionInfo.getCalories();
                totalProtein += nutritionInfo.getProtein() != null ? nutritionInfo.getProtein() : 0.0;
                totalCarbs += nutritionInfo.getCarbohydrates() != null ? nutritionInfo.getCarbohydrates() : 0.0;
                totalFat += nutritionInfo.getFat() != null ? nutritionInfo.getFat() : 0.0;
                
            } catch (Exception e) {
                logger.error("Error calculating nutrition for food item: {}", foodItem.getName(), e);
            }
        }
        
        // 更新饮食记录的营养信息
        dietRecord.setCalories(totalCalories);
        dietRecord.setProtein(totalProtein);
        dietRecord.setCarbohydrates(totalCarbs);
        dietRecord.setFat(totalFat);
    }

    @Override
    public DietRecord removeFoodItemFromDietRecord(Long dietRecordId, Long foodItemId) {
        DietRecord dietRecord = dietRecordRepository.findById(dietRecordId)
                .orElseThrow(() -> new RuntimeException("Diet record not found with id: " + dietRecordId));

        FoodItem foodItem = foodItemRepository.findById(foodItemId)
                .orElseThrow(() -> new RuntimeException("Food item not found with id: " + foodItemId));

        dietRecord.getFoodItems().remove(foodItem);
        return dietRecordRepository.save(dietRecord);
    }

    @Override
    public double calculateTotalCaloriesForUserInDateRange(Long userId, LocalDate startDate, LocalDate endDate) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found with id: " + userId));

        LocalDateTime startDateTime = startDate.atStartOfDay();
        LocalDateTime endDateTime = endDate.atTime(LocalTime.MAX);

        Double totalCalories = dietRecordRepository.calculateTotalCaloriesForUserInTimeRange(
                userId, startDateTime, endDateTime);

        return totalCalories != null ? totalCalories : 0.0;
    }

    @Override
    public Map<String, Double> calculateNutrientIntakeForUserInDateRange(Long userId, LocalDate startDate, LocalDate endDate) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found with id: " + userId));

        LocalDateTime startDateTime = startDate.atStartOfDay();
        LocalDateTime endDateTime = endDate.atTime(LocalTime.MAX);

        // 初始化营养素摄入映射
        Map<String, Double> nutrientIntake = new HashMap<>();
        
        // 使用Repository方法直接计算总营养值
        Double totalCalories = dietRecordRepository.calculateTotalCaloriesForUserInTimeRange(
                userId, startDateTime, endDateTime);
        nutrientIntake.put("calories", totalCalories != null ? totalCalories : 0.0);
        
        Double totalProtein = dietRecordRepository.calculateTotalProteinForUserInTimeRange(
                userId, startDateTime, endDateTime);
        nutrientIntake.put("protein", totalProtein != null ? totalProtein : 0.0);
        
        Double totalCarbs = dietRecordRepository.calculateTotalCarbsForUserInTimeRange(
                userId, startDateTime, endDateTime);
        nutrientIntake.put("carbohydrates", totalCarbs != null ? totalCarbs : 0.0);
        
        Double totalFat = dietRecordRepository.calculateTotalFatForUserInTimeRange(
                userId, startDateTime, endDateTime);
        nutrientIntake.put("fat", totalFat != null ? totalFat : 0.0);
        
        // 获取饮食记录，计算其他营养素
        List<DietRecord> dietRecords = dietRecordRepository.findByUserIdAndConsumptionTimeBetween(
                userId, startDateTime, endDateTime);
        
        // 初始化其他营养素
        nutrientIntake.put("fiber", 0.0);
        nutrientIntake.put("sugar", 0.0);
        nutrientIntake.put("sodium", 0.0);
        nutrientIntake.put("cholesterol", 0.0);
        
        // 计算其他营养素摄入和添加记录本身的营养值
        for (DietRecord record : dietRecords) {
            // 添加记录本身的营养值（如果有）
            if (record.getCalories() != null && record.getCalories() > 0) {
                nutrientIntake.put("calories", nutrientIntake.get("calories") + record.getCalories());
            }
            
            if (record.getProtein() != null && record.getProtein() > 0) {
                nutrientIntake.put("protein", nutrientIntake.get("protein") + record.getProtein());
            }
            
            if (record.getCarbohydrates() != null && record.getCarbohydrates() > 0) {
                nutrientIntake.put("carbohydrates", nutrientIntake.get("carbohydrates") + record.getCarbohydrates());
            }
            
            if (record.getFat() != null && record.getFat() > 0) {
                nutrientIntake.put("fat", nutrientIntake.get("fat") + record.getFat());
            }
            
            // 计算食物项的其他营养素
            for (FoodItem foodItem : record.getFoodItems()) {
                NutritionInfo nutritionInfo = nutritionInfoRepository.findByFoodItemId(foodItem.getId()).orElse(null);
                if (nutritionInfo != null) {
                    if (nutritionInfo.getFiber() != null) {
                        nutrientIntake.put("fiber", nutrientIntake.get("fiber") + nutritionInfo.getFiber());
                    }

                    if (nutritionInfo.getSugar() != null) {
                        nutrientIntake.put("sugar", nutrientIntake.get("sugar") + nutritionInfo.getSugar());
                    }

                    if (nutritionInfo.getSodium() != null) {
                        nutrientIntake.put("sodium", nutrientIntake.get("sodium") + nutritionInfo.getSodium());
                    }

                    if (nutritionInfo.getCholesterol() != null) {
                        nutrientIntake.put("cholesterol", nutrientIntake.get("cholesterol") + nutritionInfo.getCholesterol());
                    }
                }
            }
        }

        return nutrientIntake;
    }

    @Override
    public Map<String, Object> analyzeDietaryPatterns(Long userId, LocalDate startDate, LocalDate endDate) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found with id: " + userId));

        LocalDateTime startDateTime = startDate.atStartOfDay();
        LocalDateTime endDateTime = endDate.atTime(LocalTime.MAX);

        List<DietRecord> dietRecords = dietRecordRepository.findByUserIdAndConsumptionTimeBetween(
                userId, startDateTime, endDateTime);

        Map<String, Object> analysis = new HashMap<>();

        // 分析餐食类型分布
        Map<MealType, Long> mealTypeDistribution = dietRecords.stream()
                .collect(Collectors.groupingBy(DietRecord::getMealType, Collectors.counting()));
        analysis.put("mealTypeDistribution", mealTypeDistribution);

        // 分析食品类别分布
        Map<FoodItem.FoodCategory, Long> foodCategoryDistribution = new HashMap<>();
        for (DietRecord record : dietRecords) {
            for (FoodItem foodItem : record.getFoodItems()) {
                FoodItem.FoodCategory category = foodItem.getCategory();
                foodCategoryDistribution.put(category, foodCategoryDistribution.getOrDefault(category, 0L) + 1);
            }
        }
        analysis.put("foodCategoryDistribution", foodCategoryDistribution);

        // 分析每日卡路里摄入趋势
        Map<LocalDate, Double> dailyCalorieIntake = new HashMap<>();
        for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
            double calories = calculateTotalCaloriesForUserInDateRange(userId, date, date);
            dailyCalorieIntake.put(date, calories);
        }
        analysis.put("dailyCalorieIntake", dailyCalorieIntake);

        // 分析常见食品
        Map<String, Long> commonFoods = dietRecords.stream()
                .flatMap(record -> record.getFoodItems().stream())
                .collect(Collectors.groupingBy(FoodItem::getName, Collectors.counting()));

        // 获取前10个最常见的食品
        List<Map.Entry<String, Long>> topFoods = commonFoods.entrySet().stream()
                .sorted(Map.Entry.<String, Long>comparingByValue().reversed())
                .limit(10)
                .collect(Collectors.toList());

        analysis.put("commonFoods", topFoods);

        return analysis;
    }

    @Override
    public Map<String, Object> compareActualVsRecommendedIntake(Long userId, LocalDate date) {
        // 获取用户的推荐营养摄入
        Map<String, Double> recommendedIntake = userHealthProfileService.generateNutrientRequirements(userId);

        // 获取用户的实际营养摄入
        Map<String, Double> actualIntake = calculateNutrientIntakeForUserInDateRange(userId, date, date);

        // 比较实际摄入与推荐摄入
        Map<String, Object> comparison = new HashMap<>();
        comparison.put("recommended", recommendedIntake);
        comparison.put("actual", actualIntake);

        // 计算差异百分比
        Map<String, Double> differencePercentage = new HashMap<>();
        for (String nutrient : recommendedIntake.keySet()) {
            if (actualIntake.containsKey(nutrient) && recommendedIntake.get(nutrient) > 0) {
                double diff = (actualIntake.get(nutrient) / recommendedIntake.get(nutrient)) * 100 - 100;
                differencePercentage.put(nutrient, diff);
            }
        }
        comparison.put("differencePercentage", differencePercentage);

        // 生成建议
        List<String> suggestions = new ArrayList<>();

        // 卡路里建议
        if (differencePercentage.containsKey("calories")) {
            double calorieDiff = differencePercentage.get("calories");
            if (calorieDiff < -10) {
                suggestions.add("您的卡路里摄入低于推荐值，可以适当增加食物摄入量。");
            } else if (calorieDiff > 10) {
                suggestions.add("您的卡路里摄入高于推荐值，建议控制食物摄入量。");
            } else {
                suggestions.add("您的卡路里摄入在推荐范围内，继续保持！");
            }
        }

        // 蛋白质建议
        if (differencePercentage.containsKey("protein")) {
            double proteinDiff = differencePercentage.get("protein");
            if (proteinDiff < -10) {
                suggestions.add("您的蛋白质摄入不足，建议增加瘦肉、鱼、蛋、豆类等富含蛋白质的食物。");
            } else if (proteinDiff > 30) {
                suggestions.add("您的蛋白质摄入过高，建议适当减少，并确保摄入多样化的食物。");
            }
        }

        // 碳水化合物建议
        if (differencePercentage.containsKey("carbohydrates")) {
            double carbsDiff = differencePercentage.get("carbohydrates");
            if (carbsDiff < -10) {
                suggestions.add("您的碳水化合物摄入不足，建议增加全谷物、水果等食物。");
            } else if (carbsDiff > 20) {
                suggestions.add("您的碳水化合物摄入过高，建议减少精制碳水化合物的摄入，如白面包、糖果等。");
            }
        }

        // 脂肪建议
        if (differencePercentage.containsKey("fat")) {
            double fatDiff = differencePercentage.get("fat");
            if (fatDiff < -10) {
                suggestions.add("您的脂肪摄入不足，建议适当增加健康脂肪的摄入，如橄榄油、坚果等。");
            } else if (fatDiff > 20) {
                suggestions.add("您的脂肪摄入过高，建议减少油炸食品和高脂肪食物的摄入。");
            }
        }

        // 纤维建议
        if (differencePercentage.containsKey("fiber")) {
            double fiberDiff = differencePercentage.get("fiber");
            if (fiberDiff < -20) {
                suggestions.add("您的膳食纤维摄入不足，建议增加蔬菜、水果、全谷物和豆类的摄入。");
            }
        }

        comparison.put("suggestions", suggestions);

        return comparison;
    }
    
    @Override
    public Map<String, Object> getNutritionRatio(Long userId, LocalDate date, String period) {
        // 验证用户是否存在
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found with id: " + userId));

        // 创建结果Map
        Map<String, Object> result = new HashMap<>();
        result.put("period", period);
        result.put("startDate", date.toString());
        
        LocalDate startDate;
        LocalDate endDate = date;
        
        // 根据周期确定开始日期
        if ("weekly".equals(period)) {
            startDate = date.minusDays(6); // 过去一周（包括当天）
            result.put("startDate", startDate.toString());
        } else {
            startDate = date; // 默认为daily
        }
        
        result.put("endDate", endDate.toString());
        
        // 获取指定日期范围内的营养摄入数据
        Map<String, Double> nutrientIntake = calculateNutrientIntakeForUserInDateRange(userId, startDate, endDate);
        
        // 计算营养素占比
        double totalProtein = nutrientIntake.getOrDefault("protein", 0.0);
        double totalCarbs = nutrientIntake.getOrDefault("carbohydrates", 0.0);
        double totalFat = nutrientIntake.getOrDefault("fat", 0.0);
        
        // 计算总量
        double totalNutrients = totalProtein + totalCarbs + totalFat;
        
        // 计算百分比
        List<Map<String, Object>> nutritionRatio = new ArrayList<>();
        
        if (totalNutrients > 0) {
            Map<String, Object> proteinRatio = new HashMap<>();
            proteinRatio.put("name", "蛋白质");
            proteinRatio.put("value", Math.round((totalProtein / totalNutrients * 100) * 10) / 10.0);
            nutritionRatio.add(proteinRatio);
            
            Map<String, Object> carbsRatio = new HashMap<>();
            carbsRatio.put("name", "碳水化合物");
            carbsRatio.put("value", Math.round((totalCarbs / totalNutrients * 100) * 10) / 10.0);
            nutritionRatio.add(carbsRatio);
            
            Map<String, Object> fatRatio = new HashMap<>();
            fatRatio.put("name", "脂肪");
            fatRatio.put("value", Math.round((totalFat / totalNutrients * 100) * 10) / 10.0);
            nutritionRatio.add(fatRatio);
        } else {
            // 如果没有数据，设置默认值
            Map<String, Object> proteinRatio = new HashMap<>();
            proteinRatio.put("name", "蛋白质");
            proteinRatio.put("value", 0.0);
            nutritionRatio.add(proteinRatio);
            
            Map<String, Object> carbsRatio = new HashMap<>();
            carbsRatio.put("name", "碳水化合物");
            carbsRatio.put("value", 0.0);
            nutritionRatio.add(carbsRatio);
            
            Map<String, Object> fatRatio = new HashMap<>();
            fatRatio.put("name", "脂肪");
            fatRatio.put("value", 0.0);
            nutritionRatio.add(fatRatio);
        }
        
        result.put("nutritionRatio", nutritionRatio);
        
        return result;
    }
    
    @Override
    public Map<String, Object> getCalorieGoalCompletion(Long userId, LocalDate date) {
        // 验证用户是否存在
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found with id: " + userId));
        
        // 创建结果Map
        Map<String, Object> result = new HashMap<>();
        result.put("userId", userId);
        result.put("date", date.toString());
        
        // 获取用户当天的卡路里摄入量
        double caloriesConsumed = calculateTotalCaloriesForUserInDateRange(userId, date, date);
        
        // 获取用户的推荐卡路里摄入量
        Map<String, Double> recommendedIntake = userHealthProfileService.generateNutrientRequirements(userId);
        double caloriesGoal = recommendedIntake.getOrDefault("calories", 2000.0);
        
        // 计算完成百分比
        double percentage = Math.min((caloriesConsumed / caloriesGoal) * 100, 100);
        
        // 添加到结果Map
        result.put("caloriesConsumed", caloriesConsumed);
        result.put("caloriesGoal", caloriesGoal);
        result.put("percentage", Math.round(percentage * 10) / 10.0);
        
        return result;
    }
    
    @Override
    public Map<String, Object> getNutritionComparison(Long userId, LocalDate date, String period) {
        // 验证用户是否存在
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found with id: " + userId));
        
        // 创建结果Map
        Map<String, Object> result = new HashMap<>();
        result.put("userId", userId);
        result.put("period", period);
        
        // 根据周期确定日期范围
        LocalDate startDate;
        LocalDate endDate = date;
        
        if ("monthly".equals(period)) {
            // 获取当月第一天
            startDate = date.withDayOfMonth(1);
            // 获取当月最后一天
            endDate = date.withDayOfMonth(date.lengthOfMonth());
        } else {
            // 默认为weekly，获取过去一周（包括当天）
            startDate = date.minusDays(6);
        }
        
        result.put("startDate", startDate.toString());
        result.put("endDate", endDate.toString());
        
        // 获取指定日期范围内的营养摄入数据
        Map<String, Double> nutrientIntake = calculateNutrientIntakeForUserInDateRange(userId, startDate, endDate);
        
        // 获取用户的推荐营养摄入量
        Map<String, Double> recommendedIntake = userHealthProfileService.generateNutrientRequirements(userId);
        
        // 根据周期调整推荐摄入量
        int days = (int) (java.time.temporal.ChronoUnit.DAYS.between(startDate, endDate) + 1);
        for (Map.Entry<String, Double> entry : recommendedIntake.entrySet()) {
            recommendedIntake.put(entry.getKey(), entry.getValue() * days);
        }
        
        // 创建营养素对比数据
        List<Map<String, Object>> nutritionComparison = new ArrayList<>();
        
        // 添加蛋白质对比
        Map<String, Object> proteinComparison = new HashMap<>();
        proteinComparison.put("nutrient", "蛋白质");
        proteinComparison.put("recommended", recommendedIntake.getOrDefault("protein", 0.0));
        proteinComparison.put("actual", nutrientIntake.getOrDefault("protein", 0.0));
        nutritionComparison.add(proteinComparison);
        
        // 添加碳水化合物对比
        Map<String, Object> carbsComparison = new HashMap<>();
        carbsComparison.put("nutrient", "碳水化合物");
        carbsComparison.put("recommended", recommendedIntake.getOrDefault("carbohydrates", 0.0));
        carbsComparison.put("actual", nutrientIntake.getOrDefault("carbohydrates", 0.0));
        nutritionComparison.add(carbsComparison);
        
        // 添加脂肪对比
        Map<String, Object> fatComparison = new HashMap<>();
        fatComparison.put("nutrient", "脂肪");
        fatComparison.put("recommended", recommendedIntake.getOrDefault("fat", 0.0));
        fatComparison.put("actual", nutrientIntake.getOrDefault("fat", 0.0));
        nutritionComparison.add(fatComparison);
        
        result.put("nutritionComparison", nutritionComparison);
        
        return result;
    }
    
    @Override
    public Map<String, Object> getNutritionTrend(Long userId, LocalDate startDate, LocalDate endDate) {
        // 验证用户是否存在
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found with id: " + userId));

        // 创建结果Map
        Map<String, Object> result = new HashMap<>();
        List<String> dates = new ArrayList<>();
        List<Double> calories = new ArrayList<>();
        List<Double> protein = new ArrayList<>();
        List<Double> carbohydrates = new ArrayList<>();
        List<Double> fat = new ArrayList<>();

        // 遍历日期范围内的每一天
        for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
            // 获取该天的营养摄入
            Map<String, Double> nutrientIntake = calculateNutrientIntakeForUserInDateRange(userId, date, date);
            
            // 添加日期
            dates.add(date.toString());
            
            // 添加营养素数据
            calories.add(nutrientIntake.getOrDefault("calories", 0.0));
            protein.add(nutrientIntake.getOrDefault("protein", 0.0));
            carbohydrates.add(nutrientIntake.getOrDefault("carbohydrates", 0.0));
            fat.add(nutrientIntake.getOrDefault("fat", 0.0));
        }

        // 将数据添加到结果Map中
        result.put("dates", dates);
        result.put("calories", calories);
        result.put("protein", protein);
        result.put("carbohydrates", carbohydrates);
        result.put("fat", fat);

        return result;
    }
    
    @Override
    public Map<String, Object> getFoodCategoryDistribution(Long userId, LocalDate date, String period) {
        // 验证用户是否存在
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found with id: " + userId));
        
        // 创建结果Map
        Map<String, Object> result = new HashMap<>();
        result.put("userId", userId);
        result.put("period", period);
        
        // 根据周期确定日期范围
        LocalDate startDate;
        LocalDate endDate = date;
        
        if ("monthly".equals(period)) {
            // 获取当月第一天
            startDate = date.withDayOfMonth(1);
            // 获取当月最后一天
            endDate = date.withDayOfMonth(date.lengthOfMonth());
        } else {
            // 默认为weekly，获取过去一周（包括当天）
            startDate = date.minusDays(6);
        }
        
        result.put("startDate", startDate.toString());
        result.put("endDate", endDate.toString());
        
        // 获取指定日期范围内的饮食记录
        LocalDateTime startDateTime = startDate.atStartOfDay();
        LocalDateTime endDateTime = endDate.atTime(LocalTime.MAX);
        List<DietRecord> dietRecords = dietRecordRepository.findByUserIdAndConsumptionTimeBetween(
                userId, startDateTime, endDateTime);
        
        // 分析食品类别分布
        Map<FoodItem.FoodCategory, Long> categoryCountMap = new HashMap<>();
        for (DietRecord record : dietRecords) {
            for (FoodItem foodItem : record.getFoodItems()) {
                FoodItem.FoodCategory category = foodItem.getCategory();
                categoryCountMap.put(category, categoryCountMap.getOrDefault(category, 0L) + 1);
            }
        }
        
        // 转换为前端需要的格式
        List<Map<String, Object>> categoryDistribution = new ArrayList<>();
        for (FoodItem.FoodCategory category : FoodItem.FoodCategory.values()) {
            Map<String, Object> categoryData = new HashMap<>();
            categoryData.put("category", category.name());
            categoryData.put("consumptionCount", categoryCountMap.getOrDefault(category, 0L));
            categoryDistribution.add(categoryData);
        }
        
        result.put("categoryDistribution", categoryDistribution);
        
        return result;
    }
    
    @Override
    public DietRecord createDietRecordWithFoodItems(Long userId, DietRecord dietRecord, List<Map<String, Object>> foodItems) {
        // 验证用户是否存在
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found with id: " + userId));

        // 设置用户ID
        dietRecord.setUserId(userId);
        
        // 初始化营养值
        dietRecord.setCalories(0.0);
        dietRecord.setProtein(0.0);
        dietRecord.setCarbohydrates(0.0);
        dietRecord.setFat(0.0);
        
        // 保存记录以获取ID
        DietRecord savedRecord = dietRecordRepository.save(dietRecord);
        
        // 处理食品项
        double totalCalories = 0.0;
        double totalProtein = 0.0;
        double totalCarbs = 0.0;
        double totalFat = 0.0;
        
        for (Map<String, Object> foodData : foodItems) {
            String foodName = (String) foodData.get("name");
            Double amount = Double.parseDouble(foodData.get("amount").toString());
            // 每次都创建新的食品记录，不检查是否已存在
            FoodItem foodItem = new FoodItem();
            foodItem.setName(foodName);
            
            // 根据名称猜测食品类别
            FoodItem.FoodCategory category = guessFoodCategory(foodName);
            foodItem.setCategory(category);
            
            // 保存新食品
            foodItem = foodItemRepository.save(foodItem);
            
            // 直接调用DeepSeek AI计算营养信息
            Map<String, Double> nutritionData;
            try {
                nutritionData = deepSeekAIService.calculateNutrition(foodName, amount);
            } catch (Exception e) {
                logger.error("调用DeepSeek AI计算营养信息失败，使用默认值", e);
                // 如果调用失败，使用默认值
                nutritionData = new HashMap<>();
                nutritionData.put("calories", 50.0);
                nutritionData.put("protein", 50.0);
                nutritionData.put("carbohydrates", 50.0);
                nutritionData.put("fat", 50.0);
            }
            
            // 创建新的营养信息
            NutritionInfo nutritionInfo = new NutritionInfo();
            nutritionInfo.setFoodItemId(foodItem.getId());
            nutritionInfo.setServingSize(100.0); // 默认100克
            nutritionInfo.setCalories(nutritionData.getOrDefault("calories", 50.0));
            nutritionInfo.setProtein(nutritionData.getOrDefault("protein", 50.0));
            nutritionInfo.setCarbohydrates(nutritionData.getOrDefault("carbohydrates", 50.0));
            nutritionInfo.setFat(nutritionData.getOrDefault("fat", 50.0));
            
            // 保存营养信息
            nutritionInfo = nutritionInfoRepository.save(nutritionInfo);
            
            // 添加食品到饮食记录
            savedRecord.getFoodItems().add(foodItem);
            
            // 累加营养值（根据实际克数计算）
            double ratio = amount / 100.0; // 假设营养信息是基于100克计算的
            totalCalories += nutritionInfo.getCalories() * ratio;
            totalProtein += (nutritionInfo.getProtein() != null ? nutritionInfo.getProtein() : 0.0) * ratio;
            totalCarbs += (nutritionInfo.getCarbohydrates() != null ? nutritionInfo.getCarbohydrates() : 0.0) * ratio;
            totalFat += (nutritionInfo.getFat() != null ? nutritionInfo.getFat() : 0.0) * ratio;
        }
        
        // 更新饮食记录的营养信息
        savedRecord.setCalories(totalCalories);
        savedRecord.setProtein(totalProtein);
        savedRecord.setCarbohydrates(totalCarbs);
        savedRecord.setFat(totalFat);
        
        // 保存更新后的饮食记录
        return dietRecordRepository.save(savedRecord);
    }
    
    @Override
    public Map<String, Object> getBMITrend(Long userId, LocalDate startDate, LocalDate endDate) {
        // 验证用户是否存在
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found with id: " + userId));
        
        // 获取用户的健康档案
        UserHealthProfile healthProfile = userHealthProfileRepository.findByUserId(userId)
                .orElseThrow(() -> new RuntimeException("Health profile not found for user with id: " + userId));
        
        // 获取用户的身高（单位：米）
        double heightInMeters = healthProfile.getHeight() / 100.0; // 转换为米
        
        // 创建结果Map
        Map<String, Object> result = new HashMap<>();
        List<String> dates = new ArrayList<>();
        List<Double> bmiValues = new ArrayList<>();
        List<Double> weightValues = new ArrayList<>();
        
        // 获取用户在指定日期范围内的所有健康档案记录
        List<UserHealthProfile> profiles = userHealthProfileRepository.findAllByUserId(userId);
        
        // 按更新时间排序
        profiles.sort(Comparator.comparing(UserHealthProfile::getUpdatedAt));
        
        // 过滤出在日期范围内的记录
        List<UserHealthProfile> filteredProfiles = profiles.stream()
                .filter(profile -> {
                    LocalDate profileDate = profile.getUpdatedAt().toLocalDate();
                    return !profileDate.isBefore(startDate) && !profileDate.isAfter(endDate);
                })
                .collect(Collectors.toList());
        
        // 如果没有记录，使用最新的健康档案数据
        if (filteredProfiles.isEmpty()) {
            // 遍历日期范围内的每一天
            for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
                // 添加日期
                dates.add(date.toString());
                
                // 使用最新的体重数据
                double weight = healthProfile.getWeight();
                weightValues.add(weight);
                
                // 计算BMI
                double bmi = weight / (heightInMeters * heightInMeters);
                bmiValues.add(Math.round(bmi * 10) / 10.0); // 保留一位小数
            }
        } else {
            // 创建日期到健康档案的映射
            Map<LocalDate, UserHealthProfile> dateToProfileMap = new HashMap<>();
            for (UserHealthProfile profile : filteredProfiles) {
                dateToProfileMap.put(profile.getUpdatedAt().toLocalDate(), profile);
            }
            
            // 获取最早的记录日期之前的最新记录
            UserHealthProfile earliestProfile = filteredProfiles.get(0);
            LocalDate earliestDate = earliestProfile.getUpdatedAt().toLocalDate();
            
            // 如果最早的记录日期晚于开始日期，找到开始日期之前的最新记录
            if (earliestDate.isAfter(startDate)) {
                Optional<UserHealthProfile> previousProfile = profiles.stream()
                        .filter(profile -> profile.getUpdatedAt().toLocalDate().isBefore(startDate))
                        .max(Comparator.comparing(UserHealthProfile::getUpdatedAt));
                
                if (previousProfile.isPresent()) {
                    // 使用之前的记录填充开始日期之前的数据
                    for (LocalDate date = startDate; date.isBefore(earliestDate); date = date.plusDays(1)) {
                        dates.add(date.toString());
                        
                        double weight = previousProfile.get().getWeight();
                        weightValues.add(weight);
                        
                        double bmi = weight / (heightInMeters * heightInMeters);
                        bmiValues.add(Math.round(bmi * 10) / 10.0);
                    }
                }
            }
            
            // 处理有记录的日期范围
            UserHealthProfile currentProfile = earliestProfile;
            for (LocalDate date = earliestDate; !date.isAfter(endDate); date = date.plusDays(1)) {
                // 如果当前日期有新记录，更新当前使用的档案
                if (dateToProfileMap.containsKey(date)) {
                    currentProfile = dateToProfileMap.get(date);
                }
                
                // 添加日期
                dates.add(date.toString());
                
                // 添加体重数据
                double weight = currentProfile.getWeight();
                weightValues.add(weight);
                
                // 计算BMI
                double bmi = weight / (heightInMeters * heightInMeters);
                bmiValues.add(Math.round(bmi * 10) / 10.0);
            }
        }
        
        // 将数据添加到结果Map中
        result.put("userId", userId);
        result.put("dates", dates);
        result.put("bmiValues", bmiValues);
        result.put("weightValues", weightValues);
        
        return result;
    }
    
    /**
     * 根据食品名称猜测食品类别
     * @param foodName 食品名称
     * @return 猜测的食品类别
     */
    private FoodItem.FoodCategory guessFoodCategory(String foodName) {
        String lowerName = foodName.toLowerCase();
        
        // 水果
        if (lowerName.contains("苹果") || lowerName.contains("香蕉") || lowerName.contains("橙") ||
            lowerName.contains("梨") || lowerName.contains("草莓") || lowerName.contains("水果")) {
            return FoodItem.FoodCategory.FRUITS;
        }
        
        // 蔬菜
        if (lowerName.contains("菜") || lowerName.contains("西红柿") || lowerName.contains("黄瓜") ||
            lowerName.contains("胡萝卜") || lowerName.contains("生菜") || lowerName.contains("蔬菜")) {
            return FoodItem.FoodCategory.VEGETABLES;
        }
        
        // 谷物
        if (lowerName.contains("米") || lowerName.contains("面") || lowerName.contains("麦") ||
            lowerName.contains("粥") || lowerName.contains("饭") || lowerName.contains("谷物")) {
            return FoodItem.FoodCategory.GRAINS;
        }
        
        // 蛋白质食品
        if (lowerName.contains("肉") || lowerName.contains("鸡") || lowerName.contains("牛") ||
            lowerName.contains("猪") || lowerName.contains("鱼") || lowerName.contains("蛋") ||
            lowerName.contains("豆腐") || lowerName.contains("豆")) {
            return FoodItem.FoodCategory.PROTEINS;
        }
        
        // 乳制品
        if (lowerName.contains("奶") || lowerName.contains("酸奶") || lowerName.contains("奶酪") ||
            lowerName.contains("乳") || lowerName.contains("酪")) {
            return FoodItem.FoodCategory.DAIRY;
        }
        
        // 零食
        if (lowerName.contains("零食") || lowerName.contains("饼干") || lowerName.contains("薯片") ||
            lowerName.contains("巧克力") || lowerName.contains("糖")) {
            return FoodItem.FoodCategory.SNACKS;
        }
        
        // 饮料
        if (lowerName.contains("水") || lowerName.contains("茶") || lowerName.contains("咖啡") ||
            lowerName.contains("饮料") || lowerName.contains("汁") || lowerName.contains("酒")) {
            return FoodItem.FoodCategory.BEVERAGES;
        }
        
        // 默认为其他
        return FoodItem.FoodCategory.OTHER;
    }
}